import {getUContatesById,getContatesByIdcard,delUComtateById} from '../../../api/mineucontates'
// pages/adduser/mineucontates/mineucontates.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    type:0,//类型 0-游客信息选择 1-联系人信息选择
    nowCheckedNum:0,//当前勾选数量
    maxnum:0,//最大勾选数
    flag:false,//判断是否显示复选框
    rule:0,
    contatesList:[],
    checkmsg:''
  },
  //复选框点击事件！
  getCheckId(e){
    const index=e.currentTarget.dataset.index
    const list=[...this.data.contatesList];
    list[index].isChecked=!list[index].isChecked
    //判断我的缓存联系人有没有这个对象，有就删除
    if(list[index].isChecked==false){
      let storage=wx.getStorageSync('checkedContatesList')
      if(storage){
        storage=storage.filter((i)=>{
          return i.name!=list[index].name && i.idcard!=list[index].idcard
        })
        console.log(storage)
        wx.setStorageSync('checkedContatesList', storage)
      }

    }

    //获得点击复选框后，当前被选中的集合
    let list2=list.filter((item)=>{
      return item.isChecked==true
    })
    //判断是否大于最大选择数量
    if(list2.length>this.data.maxnum){//大于弹出提示
      wx.showToast({
        title: '已到最大选择数',
        icon: 'error'
      })
      list[index].isChecked=false
      this.setData({
        contatesList:list
      })
    }else{
      this.setData({
        contatesList:list
      })
      if(list[index].isChecked==true){
        this.setData({
          nowCheckedNum:this.data.nowCheckedNum+1
        })
      }else{
        this.setData({
          nowCheckedNum:this.data.nowCheckedNum-1
        })
      }
    }
  },

  smartNavigate(url, data) {
    const fullUrl = url.startsWith('/') ? url : `/${url}`;
    // const query = data ? `?${new URLSearchParams(data).toString()}` : '';
    const targetPath = fullUrl.split('?')[0]; // 去除已有参数
    
    const pages = getCurrentPages();
    const targetIndex = pages.findIndex(page => 
      page.route === targetPath.replace(/^\//, '')
    );
  
    if (targetIndex >= 0) {
      // 返回前修改数据
      let prevPage = pages[pages.length - 2];
      let list=wx.getStorageSync('checkedContatesList')
      let linkman=wx.getStorageSync('linkman')
      // let list2=this.data.contatesList
      // const newlist=[...list,...list2]
      if(this.data.type==0){
        prevPage.setData({ checkedContatesList: list }); // 设置新数据
      }else{
        prevPage.setData({ linkman: linkman }); // 设置新数据
      }
     

      console.log("navigateBack")
      wx.navigateBack({
        delta: pages.length - targetIndex - 1
      });
    } else {
      console.log("redirectto")
      wx.redirectTo({ url: fullUrl + data });
    }
  },
  

  //确认选择按钮点击
  addCheckedUser(){
    let list=[...this.data.contatesList]
    list=list.filter((item)=>{
      return item.isChecked==true//筛选出被选中联系人
    })
    if(this.data.type==0){
      let d=wx.getStorageSync('checkedContatesList')
      d=d.filter((item)=>{
        return item.name!='' || item.idcard != ''
      })
      for (let i = 0; i < list.length; i++) {
        const element = list[i];
        d.push(element)
      }
      console.log(list)
      wx.setStorageSync('checkedContatesList', d)
    }else{
      if(list.length>0){
        wx.setStorageSync('linkman', list[0])
      }
    }
    // B页面跳转逻辑
    const savedData = wx.getStorageSync('zhi');
    this.smartNavigate(`/pages/order/order`,`?ticket=${savedData.ticket}` +
    `&choose=${savedData.choose}` +
    `&bigname=${savedData.bigname}` +
    `&year=${savedData.year}`)
    // wx.redirectTo({
    //   url: `/pages/order/order?ticket=${savedData.ticket}` +
    //       `&choose=${savedData.choose}` +
    //       `&bigname=${savedData.bigname}` +
    //       `&year=${savedData.year}`
    // });
  },

  //跳转添加常用联系人页面
  adduser(){
    wx.redirectTo({
      url: '/pages/adduser/adduser',
    })
  },

  //长按事件
  handleLongPress(event) {
    console.log("长按触发", event.currentTarget.dataset.item);
    let that=this
    const data=event.currentTarget.dataset.item
    wx.showModal({
      title: '删除常用联系人：'+data.name,
      content: '确定要删除吗？',
      success(res) {
        if (res.confirm) {
          delUComtateById(data.id).then(data=>{
            wx.showToast({
              title: '删除成功',
            })
          })
          that.getMineUContates()
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }
    });
    
  },

  //页面加载获得当前用户的常用联系人
  async getMineUContates(){
    const user=wx.getStorageSync('userInfo')
    const data=await getUContatesById(user.userId)//用户id
    //呵呵我要算年龄了你现在满意了没
    data.data.list.forEach((item)=>{
      if (this.data.rule==1){//妈蛋，这么长
        this.setData({
          checkmsg:"当前票仅限成人"
        })
        let day=item.idcard.substring(6,14)
        let now=new Date()
        let age=0
        if(now.getMonth()+1>Number(day.substring(4,6))){
          age=now.getFullYear()-Number(day.substring(0,4))
        }else if(now.getMonth()+1==Number(day.substring(4,6))){
          if(now.getDay<Number(day.substring(6))){
            age=now.getFullYear()-Number(day.substring(0,4))-1
          }else{
            age=now.getFullYear()-Number(day.substring(0,4))
          }
        }else{
          age=now.getFullYear()-Number(day.substring(0,4))-1
        }
        if(age<18){
          item.isdis=true
        }else{
          item.isdis=false
        }
      }else if (this.data.rule==2) {
        this.setData({
          checkmsg:"当前票仅限儿童"
        })
        let day=item.idcard.substring(6,14)
        let now=new Date()
        let age=0
        if(now.getMonth()+1>Number(day.substring(4,6))){
          age=now.getFullYear()-Number(day.substring(0,4))
        }else if(now.getMonth()+1==Number(day.substring(4,6))){
          if(now.getDay<Number(day.substring(6))){
            age=now.getFullYear()-Number(day.substring(0,4))-1
          }else{
            age=now.getFullYear()-Number(day.substring(0,4))
          }
        }else{
          age=now.getFullYear()-Number(day.substring(0,4))-1
        }
        if(age>=18){
          item.isdis=true
        }else{
          item.isdis=false
        }
      }else if (this.data.rule==3) {
        this.setData({
          checkmsg:"当前票仅限学生购买"
        })
        if (item.role!=2) {
          item.isdis=true
        }else{
          item.isdis=false
        }
      }else if (this.data.rule==4) {
        this.setData({
          checkmsg:"当前票仅限退役军人或现役"
        })
        if (item.role!=3) {
          item.isdis=true
        }else{
          item.isdis=false
        }
      }else if (this.data.rule==5) {
        this.setData({
          checkmsg:"当前票仅限60（含60）老人"
        })
        let day=item.idcard.substring(6,14)
        let now=new Date()
        let age=0
        if(now.getMonth()+1>Number(day.substring(4,6))){
          age=now.getFullYear()-Number(day.substring(0,4))
        }else if(now.getMonth()+1==Number(day.substring(4,6))){
          if(now.getDay<Number(day.substring(6))){
            age=now.getFullYear()-Number(day.substring(0,4))-1
          }else{
            age=now.getFullYear()-Number(day.substring(0,4))
          }
        }else{
          age=now.getFullYear()-Number(day.substring(0,4))-1
        }
        if(age<60){
          item.isdis=true
        }else{
          item.isdis=false
        }
      }else{
        item.isdis=false
      }
    })
    this.setData({
      contatesList:data.data.list
    })
    // 1. 先获取原数组（避免直接修改data中的数据，确保响应式）
    let list = [...this.data.contatesList];
    for (let i = 0; i < list.length; i++) {
      const element = list[i];
      element.isChecked=false
      element.privaryIdcard=element.idcard.substring(0,4)+"***********"+element.idcard.substring(15)
      switch(element.role){
        case 0:
          element.role="成人"
          break;
        case 1:
          element.role="儿童"  
          break;
        case 2:
          element.role="学生"  
          break;
        case 3:
          element.role="残疾军人"
          break;
      }
    }
    //我操了我重新排序一下
    let isundis=[...list]
    let isdis=[...list]
    isundis=isundis.filter((item)=>{
      return item.isdis==true
    })
    isdis=isdis.filter((item)=>{
      return item.isdis==false
    })
    list=[...isdis,...isundis]
    // . 更新data，触发视图更新
    this.setData({
      contatesList: list
    } )     
    console.log(this.data.contatesList)

    //判断订单页面填写的联系人信息是否在常用联系人列
    if(this.data.type==0){//游玩人
      let arr=[]
      let fromlist=wx.getStorageSync('checkedContatesList')
      for (let i = 0; i < fromlist.length; i++) {
        const e = fromlist[i];
        arr.push(e.idcard)
      }
      
      const data=await getContatesByIdcard(arr+" ",wx.getStorageSync('userInfo').userId)
      const newlist=data.data.list
      console.log(newlist)
      let oldlist=[...this.data.contatesList]
      console.log(oldlist)
      let cnum=0//记录已经有几个联系人被选中？？？？
      for (let i = 0; i < newlist.length; i++) {
        const element = newlist[i];
        for (let j = 0; j < oldlist.length; j++) {
          const item = oldlist[j];
          if(element.idcard==item.idcard){
            item.isChecked=true
            cnum=cnum+1
            if(this.data.maxnum==0){
              this.setData({
                maxnum:cnum
              })
            }
          }
        }
      }
      this.setData({
        contatesList:oldlist,
        nowCheckedNum:cnum
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    if(options.flag=="mine"){
      this.setData({
        flag:false
      })
    }else{
      this.setData({
        flag:true
      })
    }
    //获得最大勾选数量和选择的类型
    this.setData({
      type:options.type,
      maxnum:options.maxnum,
      rule:options.rule
    })
    //查询当前用户的常用联系人
    this.getMineUContates()
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getMineUContates()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})